package com.goods.service;

import com.goods.entity.Goods;
import com.goods.entity.GoodsCategory;
import com.goods.model.Page;
import com.goods.util.DBManager;
import com.goods.util.GoodsNoUtil;
import com.goods.util.IDGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.util.*;

/**
 * 商品业务逻辑类
 * @author huangyanzhong
 * @date 2020-04-01
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    private Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private DBManager dbManager;
    @Autowired
    GoodsCategoryService goodsCategoryService;

    /**
     * 新增商品
     * @param goods
     */
    @Override
    public void insert(Goods goods) throws Exception {
        String uuid = IDGen.uuid();
        goods.setGoodsNo(GoodsNoUtil.getGoodsNo());
        goods.setCreateBy("佚名");
        if(goods.getQuantity()!=null&&goods.getQuantity()>0){
            goods.setStatus("有货");
        }
        else {
            goods.setStatus("缺货");
        }
        String sql="insert into goods(id,goods_no,category,name,quantity," +
                "price,status,create_by,create_time) values(?,?,?,?,?,?,?,?,?)";
        Object[] params=new Object[]{
                uuid,goods.getGoodsNo(),goods.getCategory(),goods.getName(),goods.getQuantity(),
                goods.getPrice(),goods.getStatus(),goods.getCreateBy(),new Date()};
        boolean success=dbManager.execute(sql,params);
        if(!success){
            throw new Exception("新增商品失败");
        }
    }

    /**
     * 修改商品
     * @param goods
     */
    @Override
    public void update(Goods goods) throws Exception{
        if(goods.getId()==null){
            throw new Exception("ID不能为空");
        }
        if(goods.getQuantity()!=null&&goods.getQuantity()>0){
            goods.setStatus("有货");
        }
        else {
            goods.setStatus("缺货");
        }
        String sql="update goods set category=?,name=?,quantity=?,"
                +"price=?,status=? where id=?";
        Object[] params=new Object[]{
                goods.getCategory(),goods.getName(),goods.getQuantity(),
                goods.getPrice(),goods.getStatus(),goods.getId()};
        boolean success=dbManager.execute(sql,params);
        if(!success){
            throw new Exception("修改商品失败");
        }
    }

    /**
     * 删除商品
     * @param id
     */
    @Override
    public void delete(String id) throws Exception{
        String sql="delete from goods where id = ? ";
        boolean success=dbManager.execute(sql,id);
        if(!success){
            throw new Exception("删除商品失败");
        }
    }

    /**
     * 获取商品详情
     * @param id
     * @return
     */
    @Override
    public Goods get(String id) throws Exception{
        String sql="select * from goods where id=?";
        List<Map<String,Object>> list=dbManager.select(sql,id);
        if(list==null||list.isEmpty()){
            return null;
        }
        Map<String,Object> map=list.get(0);
        Goods goods=parse(map);
        return goods;
    }

    /**
     * 转换
     * @param map
     * @return
     */
    private Goods parse(Map<String,Object> map){
        Goods goods=new Goods();
        goods.setId((String)map.get("id"));
        goods.setGoodsNo((String)map.get("goods_no"));
        String categoryId=(String)map.get("category");
        goods.setCategory(categoryId);
        if(categoryId!=null){
            try {
               GoodsCategory goodsCategory= goodsCategoryService.get(categoryId);
               if(goodsCategory!=null){
                   String name=goodsCategory.getName();
                   goods.setCategoryName(name);
               }
            }catch (Exception e){
                logger.error(e.toString());
            }
        }
        goods.setName((String)map.get("name"));
        goods.setQuantity((Long)map.get("quantity"));
        goods.setPrice((BigDecimal)map.get("price"));
        goods.setCreateBy((String)map.get("create_by"));
        goods.setCreateTime((Date)map.get("create_time"));
        goods.setStatus((String)map.get("status"));
        return goods;
    }

    /**
     * 查询商品
     * @param sample
     * @param page
     * @return
     */
    @Override
    public List<Goods> query(Goods sample, Page page) throws Exception{
        Map<String,Object> result=getSqlAndParams(sample);
        String psql=(String)result.get("sql");
        List params=(List)result.get("params");
        String sql="select * from goods where 1=1 "+psql;
        List<Map<String,Object>> list=dbManager.selectByPage(sql,params.toArray(),page);
        if(list==null||list.isEmpty()){
            return new ArrayList<>();
        }
        List<Goods> goods=new ArrayList<>();
        for(Map<String,Object> map:list){
            goods.add(parse(map));
        }
        return goods;
    }

    /**
     * 统计商品
     * @param sample
     * @return
     */
    @Override
    public long count(Goods sample) throws Exception{
        Map<String,Object> result=getSqlAndParams(sample);
        String psql=(String)result.get("sql");
        List params=(List)result.get("params");
        String sql="select count(id) from goods where 1=1 "+psql;
        long count=dbManager.getRowsCount(sql,params.toArray());
        return count;
    }

    /**
     * 获取查询参数和sql
     * @param sample
     * @return
     */
    private Map<String,Object> getSqlAndParams(Goods sample){
        List params=new ArrayList();
        StringBuffer sql=new StringBuffer();
        if(!StringUtils.isEmpty(sample.getGoodsNo())){
            sql.append("and goods_no=? ");
            params.add(sample.getGoodsNo().trim());
        }
        if(!StringUtils.isEmpty(sample.getStatus())){
            sql.append("and status=? ");
            params.add(sample.getStatus().trim());
        }
        if(!StringUtils.isEmpty(sample.getCategory())){
            sql.append("and category=? ");
            params.add(sample.getCategory().trim());
        }
        if(!StringUtils.isEmpty(sample.getName())){
            sql.append("and name=? ");
            params.add(sample.getName().trim());
        }
        if(!StringUtils.isEmpty(sample.getPrice())){
            sql.append("and price=? ");
            params.add(sample.getPrice());
        }
        if(!StringUtils.isEmpty(sample.getQuantity())){
            sql.append("and quantity=? ");
            params.add(sample.getQuantity());
        }
        if(!StringUtils.isEmpty(sample.getCreateBy())){
            sql.append("and create_by=? ");
            params.add(sample.getCreateBy().trim());
        }
        if(!StringUtils.isEmpty(sample.getCreateTime())){
            sql.append("and create_time=?");
            params.add(sample.getCreateTime());
        }
        Map<String,Object> result=new HashMap<>();
        result.put("sql",sql.toString());
        result.put("params",params);
        return result;
    }

}
